import { Controller, Get, Query, Res } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiQuery } from '@nestjs/swagger';
import { Response } from 'express';
import { NoAuth } from '../../decorators/auth.decorator';
import { SwaggerFilterService } from './swagger-filter.service';

@ApiTags('系统-Swagger文档')
@Controller('swagger-filter')
export class SwaggerFilterController {
    constructor(private readonly swaggerFilterService: SwaggerFilterService) {}

    @Get('json')
    @NoAuth()
    @ApiOperation({
        summary: '获取过滤后的 Swagger JSON',
        description: '根据标签和路径前缀过滤 Swagger API 文档'
    })
    @ApiQuery({
        name: 'tags',
        required: false,
        description: '过滤的标签数组，支持多个标签，例如: tags=admin端-管理员用户,admin端-角色管理',
        type: String
    })
    @ApiQuery({
        name: 'prefix',
        required: false,
        description: '过滤的路径前缀，例如: prefix=/admin 或 prefix=/app',
        type: String
    })
    @ApiQuery({
        name: 'excludeTags',
        required: false,
        description: '排除的标签数组，支持多个标签',
        type: String
    })
    @ApiQuery({
        name: 'excludePrefix',
        required: false,
        description: '排除的路径前缀',
        type: String
    })
    async getFilteredSwaggerJson(
        @Query('tags') tags?: string,
        @Query('prefix') prefix?: string,
        @Query('excludeTags') excludeTags?: string,
        @Query('excludePrefix') excludePrefix?: string,
        @Res() res?: Response,
    ) {
        const filteredDocument = await this.swaggerFilterService.getFilteredDocument({
            tags: tags ? tags.split(',').map(tag => tag.trim()) : undefined,
            prefix,
            excludeTags: excludeTags ? excludeTags.split(',').map(tag => tag.trim()) : undefined,
            excludePrefix,
        });

        res.setHeader('Content-Type', 'application/json');
        return res.json(filteredDocument);
    }

    @Get('admin-json')
    @NoAuth()
    @ApiOperation({
        summary: '获取 Admin 端 Swagger JSON',
        description: '专门为 Admin 管理端提供的 API 文档'
    })
    async getAdminSwaggerJson(@Res() res?: Response) {
        const filteredDocument = await this.swaggerFilterService.getFilteredDocument({
            prefix: '/admin',
        });

        res.setHeader('Content-Type', 'application/json');
        return res.json(filteredDocument);
    }

    @Get('app-json')
    @NoAuth()
    @ApiOperation({
        summary: '获取 App 端 Swagger JSON',
        description: '专门为 App 客户端提供的 API 文档'
    })
    async getAppSwaggerJson(@Res() res?: Response) {
        const filteredDocument = await this.swaggerFilterService.getFilteredDocument({
            prefix: '/app',
        });

        res.setHeader('Content-Type', 'application/json');
        return res.json(filteredDocument);
    }
}
